<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title>Dojox SortList Test</title>
	<style type="text/css">
		@import "dojoroot/dojo/resources/dojo.css";
		@import "dojoroot/dijit/themes/tundra/tundra.css";
		@import "dojoroot/dijit/themes/dijit.css";
		@import "dojoroot/dijit/tests/css/dijitTests.css"; 
		@import "SortList/SortList.css";
	</style>

	<script type="text/javascript" src="dojoroot/dojo/dojo.js" djConfig="parseOnLoad: true"></script>
	<script type="text/javascript" src="dojoroot/dijit/tests/_testCommon.js"></script>
	<script type="text/javascript" src="PlayListSortList/SortList.js"></script>
	<script type="text/javascript" src="PlayListsSortList/SortList.js"></script>
	<script type="text/javascript" src="youtubestore/youtubeStore.js"></script>
	<script type="text/javascript" src="SearchSortList/SortList.js"></script>
	<script type="text/javascript" src="PlayListWriteStore/PlayListWriteStore.js"></script>
	
	<script type="text/javascript">
		dojo.require("dijit.layout.ContentPane");
		dojo.require("dijit.layout.StackContainer");
		dojo.require("dijit.layout.SplitContainer");
		dojo.require("dojo.data.ItemFileReadStore"); 
		dojo.require("dojo.parser");	// scan page for widgets and instantiate them
		dojo.require("dijit.form.Button");
       dojo.require("dijit.Dialog");
       dojo.require("dijit.form.TextBox");
	   dojo.require("dijit.Tooltip");
	   dojo.require("dijit.Menu");
	   dojo.require("dijit.form.ComboBox");
	   
		var username = "";
		var isDragging = false;
		var isSearch = false; 
		
		// initalize youtube store
		var flickrStore = new dojox.data.YouTubeStore();
		
		function selectChild(tabNode) {
			stack.selectChild(tabNode.id);
			dijit.focus(dojo.byId('videoDialog'));
			isSearch = false;
		}
		
		function deletePlaylist(playlist_name) {
		// step 1: make a get request for a playlist deletion
		var url = "deletePlaylist.php";
		dojo.xhrGet({
				url: url, 
				load: function(data) { console.debug(data); },
				error: function() { console.debug("An error has occurred"); }, 
				content: { playlist: playlist_name }
			});
		}
		
		function savePlaylist(currentPlaylist) {
			// step 1: initialize a writestore for saving to file and get all nodes from current
			// 		   playlist
			var nodes = currentPlaylist.source.getAllNodes();
			var data = { "items": [] };
			var write_source = new dojox.data.PlayListWriteStore({ data: data }); 
			write_source.fetch({});
					
			// iterate through the nodes of the playlist and insert them into writestore
			for (var i=0;i<nodes.length;i++) {
				var currentItem = currentPlaylist.source.getItem(nodes[i].id);
				currentItem = currentItem.data;
						
				write_source.newItem(currentItem);
			};
			// finally, save the playlist onto database
			write_source.playlist = currentPlaylist.name;
			write_source.save();
		}
		
		function mouseDown(currentPlaylist) {
			if (isDragging) {
				//alert("event activated");
				var nodes = dojo.dnd.manager().nodes;
				var source = dojo.dnd.manager().source;
				
				var jsnode = source.getItem(nodes[0].id);
				console.debug("jsnode: " + jsnode.data);
				currentPlaylist.source.insertNodes(false, [jsnode.data]);
				isDragging = false;
			} 
		}
		
		function deleteSong(currentPlaylist) {
			// first remove the song from the current playlist
			var removeId = currentPlaylist.current.id; 
			currentPlaylist.containerNode.removeChild(dojo.byId(removeId));
			currentPlaylist.source.delItem(removeId); 
			
			// then save to server
			savePlaylist(currentPlaylist); 
		}
		
		function loadPlaylists(data) {
		// summary: load the list of playlists and their associated individual playlist
		// 			content
		
		// step 1: parse the json content
		// 		   for each playlist, extract and append playlist name to list of playlist
		//		  					  construct a new stack container for the songs of the playlist
		//							  and add an associated onclick event to activate the playlist
			var arr_playlists =  eval('('+data+')');
			// var arr_nameNode = new Array();
			// var arr_tabNode = new Array();
			
			for(var i=0;i<arr_playlists.length;i++) {
				
				// insert the playlist name into the list of playlists
				var current_playlist = arr_playlists[i];
				var nameNode = document.createElement('li');
				nameNode.id = dojo.dnd.getUniqueId();
				nameNode.innerHTML = current_playlist.name;
				lst_playlists.source.insertNodes(false, [nameNode]);
				
				// now, we make a new tab for the current loading playlist and the dojox widget
				// that comes with it
				var tabNode = dojo.doc.createElement('div');
				tabNode.id = dojo.dnd.getUniqueId();
				var currentTab = new dijit.layout.ContentPane({title: current_playlist.name}, tabNode);
				currentTab.startup();
				
				var node = document.createElement('div');
				var currentPlaylist = new dojox.widget.PlayListSortList({title: current_playlist.name, copyOnly: false}, node);
				currentPlaylist.name = current_playlist.name;
				currentPlaylist.startup();
				
				currentTab.setContent(currentPlaylist.domNode);
				stack.addChild(currentTab);
				
				// iterate through the current playlist, add the items to the newly created playlist 
				var arr_playlist = (eval(current_playlist)).content.items;
				
				for(var j=0;j<arr_playlist.length;j++) {
					currentPlaylist.source.insertNodes(false, [arr_playlist[j]]);
				}
				
				currentPlaylist.reColor(); 
				
				// finally associate the current item on the list of playlists with its playlist
				dojo.connect(nameNode, 'onclick', dojo.hitch(null, selectChild, tabNode));
				
				// finally, associate the drag and drop of list of playlist with adding a particular item 
				// to the selected item to the selected playlist
				dojo.connect(nameNode, 'onmouseup', dojo.hitch(null, mouseDown, currentPlaylist));
				
				// now finally set up dnd and saving action for the playlist
				dojo.connect(currentPlaylist.source, "onDndDrop", dojo.hitch(null, savePlaylist, currentPlaylist)); 
				
				// this is now the last finally, add sub-menu for the playlist themselves
				var plMenu = new dijit.Menu({targetNodeIds:[currentPlaylist.domNode.id]});
			   var mItem1 = new dijit.MenuItem({label:"Delete Selected Song"});
				
			   dojo.connect(mItem1, "onClick", dojo.hitch(null, deleteSong, currentPlaylist));
			   
				plMenu.addChild(mItem1);
			   plMenu.startup();
			}
			
			// finally, record whenever a dragging event start and stop 
			dojo.subscribe("/dnd/start", function(source){
				//dijit.focus(lst_playlists);
				//dijit.focus(lst_playlists.containerNode);
				isDragging = true;
			});
			
			dojo.subscribe("/dnd/drop", function(source){
				isDragging = false;
			});
			
			dojo.subscribe("/dnd/cancel", function() {
				isDragging = false;
			});
			
			/*dojo.subscribe("/dnd/source/over", function(source){
				console.debug("source over: " + source);
			});*/
		}
		
		function addOption(selectbox,text,value )
		{
			var optn = document.createElement("OPTION");
			optn.text = text;
			optn.value = value;
			selectbox.options.add(optn);
		}
		
		
		function loadAllPlaylists(data) {
			var selectBox = dojo.byId("all_playlists");
			var arr_playlists =  eval('('+data+')');
			
			for(var i=0;i<arr_playlists.length;i++) {
				addOption(selectBox, arr_playlists[i].name, arr_playlists[i].id);
			}
		}
		
		function loadDemandedPlaylist(data) {
		
			// now, we make a new tab for the current loading playlist and the dojox widget
			// that comes with it
			var tabNode = dojo.doc.createElement('div');
			tabNode.id = dojo.dnd.getUniqueId();
			var currentTab = new dijit.layout.ContentPane({title: 'Random'}, tabNode);
			currentTab.startup();
				
			var node = document.createElement('div');
			var currentPlaylist = new dojox.widget.PlayListSortList({title: 'Random', copyOnly: false}, node);
			currentPlaylist.startup();
				
			currentTab.setContent(currentPlaylist.domNode);
			stack.addChild(currentTab);
				
			// iterate through the current playlist, add the items to the newly created playlist 
			var current_playlist = eval('('+data+')');
			var arr_playlist = (eval(current_playlist)).items;
			//var arr_playlist = eval('('+data+')');
			//arr_playl
	
			for(var j=0;j<arr_playlist.length;j++) {
				currentPlaylist.source.insertNodes(false, [arr_playlist[j]]);
			}
				
			currentPlaylist.reColor(); 
			
			// select this playlist
			stack.selectChild(tabNode.id);
		}
		
		function init(){
			// TO-DO: assign the username of the user via TemplatePower
			// step 1: load json content for the user
			
			var url = "loadPlaylists.php?username="+username;
			dojo.xhrGet({
				url: url, 
				load: loadPlaylists,
				error: function() { console.debug("An error has occurred"); }
			});
			
			// step 2: add a search button for the user
			
			var selectWrapperNode = document.createElement('li');
			selectWrapperNode.innerHTML = "Other People's Playlists: ";
			var selectNode = document.createElement('select');
			selectNode.style.width = "150px";
			selectNode.id = 'all_playlists';
			
			var url = "loadAllPlaylists.php";
			dojo.xhrGet({
				url: url, 
				load: loadAllPlaylists, 
				error: function() { console.debug("An error has occurred"); }
			});
			
			selectWrapperNode.appendChild(selectNode);
			lst_playlists.containerNode.appendChild(selectWrapperNode);
			
			
			dojo.connect(selectNode, 'onchange', function() {
				var playlist_id = dojo.byId('all_playlists').value;
				var url = "loadSinglePlaylist.php";
				dojo.xhrGet({
					url: url, 
					load: loadDemandedPlaylist,
					error: function() { console.debug("An error has occurred"); }, 
					content: { id: playlist_id }
				});
			});
			
			var nameNode = document.createElement('li');
			nameNode.id = dojo.dnd.getUniqueId();
			nameNode.innerHTML = "Search YouTube:";
			//lst_playlists.source.insertNodes(false, [nameNode]);
			lst_playlists.containerNode.appendChild(nameNode);
			
			var tabNode = dojo.doc.createElement('div');
			tabNode.id = "search"
			var currentTab = new dijit.layout.ContentPane({title: "Search"}, tabNode);
			currentTab.startup();
				
			var node = document.createElement('div');
			var currentPlaylist = new dojox.widget.SearchSortList({title: "search results", copyOnly: false}, node);
			currentPlaylist.startup();
			
			currentTab.setContent(currentPlaylist.domNode);
			stack.addChild(currentTab);
			
			var req= {  query: {vq:"music video",
								 startindex: "1",
								 maxresults: "20"}
					};
			
			currentPlaylist.setDataStore(flickrStore, req);
			
			dojo.connect(nameNode, "onclick", function() { 
				if (!isSearch) { 						// only expand a new search textbox only if we weren't previously on the search node
						stack.selectChild("search"); 
						
						while (nameNode.firstChild) 
						{
							nameNode.removeChild(nameNode.firstChild);
						};
						
						nameNode.innerHTML = 'Search Results : <input id="searchtext" type=text></input>';
						
						dojo.connect(dojo.byId('searchtext'), "onblur", function() {
							if (!isSearch) {
								nameNode.innerHTML = 'Search Results';
							}
						});
						
						dojo.connect(dojo.byId('searchtext'), 'onkeypress', function (evt) {
							key = evt.keyCode;
							if(key == dojo.keys.ENTER) {
								var req = {
										query: {vq: dojo.byId('searchtext').value, 
												startindex: "1", 
												maxresults: "20"}
									};
							currentPlaylist.setDataStore(flickrStore, req);
							}
						});
						
						dijit.focus(dojo.query('input', nameNode.domNode)[0]);
						
						isSearch = true;
					}
				} );
			
			
			
			// add sub-menu for the list of playlists
			//alert(lst_playlists.containerNode.id);
			//lst_playlists.containerNode.id = dojo.dnd.getUniqueId();
			//alert(lst_playlists.containerNode);
			var pMenu = new dijit.Menu({targetNodeIds:[lst_playlists.bodyWrapper]});
           var mItem1 = new dijit.MenuItem({label:"New Playlist"});
			var mItem2 = new dijit.MenuItem({label:"Delete Selected Playlist"});
			
           dojo.connect(mItem1, "onClick", function(){
				newplaylist.show(); 
			}
			);
			dojo.connect(mItem2, "onClick", function() {
				var removeId = lst_playlists.current.id; 
				deletePlaylist(dojo.byId(removeId).innerHTML);
				lst_playlists.containerNode.removeChild(dojo.byId(removeId));
				lst_playlists.source.delItem(removeId); 
				
			});
			pMenu.addChild(mItem1);
			pMenu.addChild(mItem2); 
           pMenu.startup();
		   
		   // show the username dialog
		   
		}
		
		dojo.addOnLoad(init);
		
	
	</script>
</head>
<body>
		
<div dojoType="dijit.layout.SplitContainer"
                orientation="horizontal"
                sizerWidth="7"
                activeSizing="true" layoutAlign="client"
                style="border: 1px solid #bfbfbf; width: 100%; height: 385px;">
                
				<div id="videoDialog" jsid="videoDialog" dojotype="dijit.layout.ContentPane" sizeMin="0" sizeShare="35" style="overflow: none">
					<div class="sortListTitle">Video</div>
					<div id="videoContent" jsid="videoContent" class="sortListBodyWrapper" align="center"></div>
				</div>
				<div id="lst_playlists_pane" jsid="lst_playlists_pane" dojoType="dijit.layout.ContentPane" sizeMin="0" sizeShare="15" style="overflow: none">		
						<div id="playlist" jsid="lst_playlists" dojoType="dojox.widget.PlayListsSortList" title="Playlist" style="width:100%; height:100%; overflow: none" key="title">
						</div>
				</div>
				<div dojoType="dijit.layout.ContentPane" sizeMin="0" sizeShare="50">
					<div jsId = "stack" id="stackContainer" dojoType="dijit.layout.StackContainer"
							style="width: 100%; border: 0px solid #9b9b9b; height: 100%; margin: 0; padding: 0;">
					</div>
				</div>
</div>			

<div jsid="newplaylist" dojoType="dijit.Dialog" id="newplaylist" title="New Playlists">
    <table>
        <tr>
        <td><label for="name">New Playlist Name: </label></td>
                <td><input id="newplaylist_text" dojoType="dijit.form.TextBox" type="input"></td>
		</tr>
				<tr>
					<td colspan="2" align="center">
                        <button dojoType=dijit.form.Button type="submit" jsid="newplaylist_ok">OK
							<script type="dojo/method" event="onClick">
								// step 1: add the node
								var nameNode = document.createElement('li');
								nameNode.id = dojo.dnd.getUniqueId();
								var playlistName = dojo.byId("newplaylist_text").value; 
								nameNode.innerHTML = playlistName; 
								
								// step 2: create a empty playlist and hook up the node to that playlist 
								var tabNode = dojo.doc.createElement('div');
								tabNode.id = dojo.dnd.getUniqueId();

								var newTab = new dijit.layout.ContentPane({title: playlistName}, tabNode);
								newTab.startup();
				
								//var node = document.createElement('div');
								var newPlaylist = new dojox.widget.PlayListSortList({title: 'test', copyOnly: false});
								newPlaylist.name = playlistName; 
								newPlaylist.startup();
				
								newTab.setContent(newPlaylist.domNode);
								stack.addChild(newTab);
								
								lst_playlists.source.insertNodes(false, [nameNode]);
								
								// finally associate the current item on the list of playlists with its playlist
								dojo.connect(nameNode, 'onclick', dojo.hitch(null, selectChild, newTab.domNode));
								
								// finally, associate the drag and drop of list of playlist with adding a particular item 
								// to the selected item to the selected playlist
								dojo.connect(nameNode, 'onmouseup', dojo.hitch(null, mouseDown, newPlaylist));
								
								// finally, reconnect with the dragging event start and stop 
								dojo.subscribe("/dnd/start", function(source){
									isDragging = true;
								});
								
								dojo.subscribe("/dnd/drop", function(source){
									isDragging = false;
								});
								
								// now finally set up dnd and saving action for the playlist
								dojo.connect(newPlaylist.source, "onDndDrop", dojo.hitch(null, savePlaylist, newPlaylist)); 
							</script>
						</button>
					</td>
				</tr>
    </table>
</div>

</body>
</html>
